package top.knos.od.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

public class JsonUtil {
    static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 忽略json串中多余的字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    }

    public static <T> T parseObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readerFor(clazz).readValue(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String writeAsJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> jsonString2List(String jsonString, Class<T> clazz) {
        try {
            JavaType javaType = getObjectiveJavaType(List.class, clazz);
            return objectMapper.readerFor(javaType).readValue(jsonString);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对象转换为json字符串,忽略空值
     */
    public static String writeAsJsonStringIgnoreNull(Object object) {
        try {
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取集合的JavaType
     *
     * @param collectionClass
     * @param elementClasses
     * @return
     */
    public static JavaType getObjectiveJavaType(Class<?> collectionClass,
                                                Class<?>... elementClasses) {
        return objectMapper.getTypeFactory()
                .constructParametricType(collectionClass, elementClasses);
    }
}
